package com.fyf.game.net.serui;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.je.log.JLog;
import org.je.ufo.Sleep;
import com.fyf.game.net.server.MessageServer;

/**
 * @author fanyifeng
 */
public class ServerUI extends JFrame implements WindowListener
{
	private static final long	serialVersionUID	= 1L;
	private final ShowCanvas	canvas;
	private boolean				isShow				= false;
	private MessageServer		ser;

	public ServerUI(MessageServer ser) {
		super("消息广播服务器");
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.ser = ser;
		int w = 400, h = 300;
		this.setBounds(20, 20, w, h);
		this.setLayout(null);
		canvas = new ShowCanvas(2, 2, w - 10, h - 30, ser);
		this.add(canvas);
		this.setResizable(false);
		this.addWindowListener(this);
	}

	public void startServer() {
		synchronized(this) {
			if (isShow)
				return;
			isShow = true;
		}
		this.setVisible(true);

		Thread t = new Thread(new Runnable() {
			public void run() {
				while (true) {
					if (ser.getRunEnvir().closeCount.get() >= 1 + ser.getRunEnvir().transporterCount()) {
						ServerUI.this.dispose();
					}
					Sleep.millis(100);
					canvas.repaint();
				}
			}
		});
		t.setDaemon(true);
		t.start();
		ser.start();
	}

	public void windowClosing(WindowEvent e) {
		int rst = JOptionPane.showConfirmDialog(this, "选项", "确定退出", JOptionPane.YES_NO_OPTION);
		if (rst == 0) {
			ser.close();
		}
	}

	public void windowClosed(WindowEvent e) {
		JLog.out("程序已经退出");
		System.exit(0);
	}

	public void windowOpened(WindowEvent e) {}

	public void windowIconified(WindowEvent e) {}

	public void windowDeiconified(WindowEvent e) {}

	public void windowActivated(WindowEvent e) {}

	public void windowDeactivated(WindowEvent e) {}
}
